<template>
	<view class="content" :style="{'padding-top':top+'px','min-height':windowheight+'px'}">
		<Navbar title="订单结算" bgColor="#da708b" :backIcon="false" style="color: #ffffff;z-index: 1;"></Navbar>
		<view class="order_balance">
			<uni-card :is-shadow="true" title="选购明细" margin="10rpx">
				<view class="photo_list">
					<view class="photol_item" v-for="(item,index) in photolists" :key="index">
						<image :src="item.photoWatermarkUrl"></image>
					</view>
				</view>
				<view class="order_info">共{{photoNum}}件，合计：￥{{orderAmount}}</view>
			</uni-card>
			<uni-card margin="10rpx" class="coupon" @click="selectCoupon">
				<view class="couponLeft">优惠券</view>
				<view class="couponRight" v-if="numbers" style="color:#e77c90;">-{{numbers}}元</view>
				<view class="couponRight" v-else-if="discount" style="color:#e77c90;">打{{discount*10}}折</view>
				<view class="couponRight" v-else>{{numberOfCoupons}}张可用</view>
			</uni-card>
			<uni-card :is-shadow="true" title="支付方式" margin="10rpx">
				<view class="payway">
					<image
						src="http://zzqjt.oss-cn-hangzhou.aliyuncs.com/templates/client/res/d0ff7da4d6fa47e18da0dc99c01e21d1-wechatpay.png">
					</image>
					<radio :checked="true"></radio>
				</view>
			</uni-card>
		</view>
		<view class="balance_bottom">
			<view class="balab_txt">实付金额：￥{{payAmount}}</view>
			<view class="balab_favorable" v-if="discountAmount">优惠金额：￥{{discountAmount}}</view>
			<view class="balab_btn">
				<button type="default" size="mini" @tap.stop="topay" :disabled="isdisabled">立即支付</button>
			</view>
		</view>
	</view>
</template>
<script setup>
	import { ref,onMounted } from 'vue'
	import {
		onLoad,
		onHide,
		onShow
	} from '@dcloudio/uni-app'
	const baseUrl = getApp().globalData.baseUrl
	const title=ref('Hello')
	const windowheight=ref()
	const platform = ref()
	const statusBar = ref()
	const customBar = ref()
	const top = ref()
	const sel_photoid = ref([1, 2, 3])
	const orderAmount = ref(24.00)
	const payAmount = ref(24.44)
	const photoNum = ref(0)
	const photoIds = ref()
	const isdisabled = ref(false)
	const numberOfCoupons=ref(0)
	const numbers=ref()
	const discount=ref()
	const coupons = ref([])
	const discountAmount=ref()
	const couponNo=ref()
	const favorable=ref()
	const photolists = ref([{
			id: 1,
			photoUrl: "../../static/logo.png"
		},
		{
			id: 2,
			photoUrl: "../../static/logo.png"
		},
	])
	const selectCoupon = () => {
		uni.navigateTo({
			url: "/pages/coupon/coupon?orderAmount="+orderAmount.value
		})
	}
	const topay = () => {
		isdisabled.value = true
		console.log(isdisabled.value)
		let orderno = Date.now().toString() + (parseInt(Math.random() * 999) + 1000).toString().substr(1);
		//console.log(orderno)
		const nums = getNonceStr()
		const time = Date.now()
		console.log(nums, time)
		console.log(0, getApp().globalData.album)
		let user_info = JSON.parse(uni.getStorageSync("user_info"))
		console.log(couponNo.value)
		if(couponNo.value){
			favorable.value=true
		}else{
			favorable.value=false
			couponNo.value=null
		}
		console.log(favorable.value)
		uni.request({
			url: getApp().globalData.baseUrl + "/pay/generate/record",
			method: "POST",
			header: {
				'content-type': 'application/json',
				'Access-Control-Allow-Origin': "*",
				'Authorization': uni.getStorageSync('token')
			},
			data: {
				// openid: user_info.openId,
				// out_trade_no: orderno,
				// total_fee: parseInt(parseFloat(payAmount.value) * 100),
				// nonce_str: getNonceStr()
				shootAddressId: getApp().globalData.album.shootAddressId,
				photoIds: photoIds.value,
				albumId: getApp().globalData.album.id,
				clientNo: getApp().globalData.album.clientNo,
				nonceStr: nums,
				timestamp: time,
				favorable:favorable.value,
				couponNo: couponNo.value
			},
			success: (res) => {
				console.log(res)
				const shootRecordId = res.data.value.shootRecordId
				if (res.data.value.needPay === false) {
					uni.request({
						url: getApp().globalData.baseUrl +
							"/album/upd/recordpay",
						header: {
							'content-type': 'application/json',
							'Access-Control-Allow-Origin': "*",
							'Authorization': uni.getStorageSync('token')
						},
						data: {
							photographerId: getApp().globalData.album
								.photographerId,
							shootRecordId: shootRecordId,
							pay: true,
							favorable:favorable.value,
							couponNo: couponNo.value,
							photoIds: photoIds.value,
						},
						method: "POST",
						success: (res) => {
							console.log(2)
							uni.showToast({
								title: "支付成功！"
							})
							setTimeout(() => {
								uni.navigateBack({
									delta: 2
								})
							}, 1000)
						},
						fail: (err) => {
							console.log(3)
							uni.showToast({
								title: "支付失败！"
							})
							isdisabled.value = false
							setTimeout(() => {
								uni.navigateBack({
									delta: 2
								})
							}, 1000)
						}
					});
				} else {
					uni.requestPayment({
						timeStamp: JSON.stringify(time),
						nonceStr: nums,
						package: res.data.value.package,
						signType: "RSA",
						paySign: res.data.value.paySign,
						success: (res) => {
							uni.request({
								url: getApp().globalData.baseUrl +
									"/album/upd/recordpay",
								header: {
									'content-type': 'application/json',
									'Access-Control-Allow-Origin': "*",
									'Authorization': uni.getStorageSync('token')
								},
								data: {
									photographerId: getApp().globalData.album
										.photographerId,
									shootRecordId: shootRecordId,
									pay: true,
									favorable:favorable.value,
									couponNo: couponNo.value,
									photoIds: photoIds.value,
								},
								method: "POST",
								success: (res) => {
									console.log(2)
									uni.showToast({
										title: "支付成功！"
									})
									setTimeout(() => {
										uni.navigateBack({
											delta: 2
										})
									}, 1000)
								},
								fail: (err) => {
									console.log(3)
									uni.showToast({
										title: "支付失败！"
									})
									isdisabled.value = false
									setTimeout(() => {
										uni.navigateBack({
											delta: 2
										})
									}, 1000)
								}
							});
						},
						fail: (err) => {
							console.log(4)
							uni.showToast({
								title: "支付失败！",
								icon: "error"
							})
							setTimeout(() => {
								uni.navigateBack({
									delta: 2
								})
							}, 1000)
							isdisabled.value = false
						},
					})
				}
			},
			fail: (err) => {
				console.log(err)
			}
		})
	}
	const getNonceStr = () => {
		let chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
			'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
		];
		let nums = '';
		for (var i = 0; i < 32; i++) {
			var id = parseInt(Math.random() * 35);
			nums += chars[id];
		}
		console.log(nums)
		return nums;
	}
	const getColumnHeight=()=>{
		uni.getSystemInfo({
			success(res) {
				console.log(res)
				platform.value = res.platform
				windowheight.value=res.screenHeight
				// #ifdef MP-WEIXIN
				statusBar.value = res.statusBarHeight
				const custom = wx.getMenuButtonBoundingClientRect()
				customBar.value = custom.bottom + custom.top - res.statusBarHeight
				// #endif
				// #ifdef APP-PLUS
				statusBar.value = res.statusBarHeight
				customBar.value = res.statusBarHeight + 45
				// 这里是在安卓手机上加上 3 像素（当时好像是在安卓水滴屏上，系统导航栏高度较低才加上去的，大家可以真机自己调试一下）
				if (res.platform == "android") {
					statusBar.value += 3
					customBar.value += 3
				}
				// #endif
			}
		})
		top.value = customBar.value
		windowheight.value=windowheight.value-top.value
		//console.log(statusBar.value, customBar.value, top.value,windowheight.value)
	}
	onLoad((opts) => {
		couponNo.value=""
		photoIds.value = getApp().globalData.newchk_imgs.map(item => item.id)
		console.log(1, opts)
		//console.log(photoIds.value)
		//console.log(getApp().globalData.album)
		orderAmount.value = opts.amount
		payAmount.value = opts.amount
		console.log(getApp().globalData.newchk_imgs)
		photolists.value = getApp().globalData.newchk_imgs
		photoNum.value = photolists.value.length
		sel_photoid.value = getApp().globalData.newchk_imgs
	})
	onShow(()=>{
		const now = new Date().getTime()
		numberOfCoupons.value=0
		if (!uni.getStorageSync('token') || now > uni.getStorageSync('expireTime')) {
			uni.reLaunch({
				url: "/pages/login/login"
			})
		}else{
			numberOfCoupons.value=0
			uni.request({
				url: getApp().globalData.baseUrl + "/coupon/list",
				method: "POST",
				header: {
					'content-type': 'application/json',
					'Access-Control-Allow-Origin': "*",
					'Authorization': uni.getStorageSync('token')
				},
				data: {
					clientNo: JSON.parse(uni.getStorageSync("user_info")).client_no,
					couponStatus:"UNUSED"
				},
				success: (res) => {
					console.log(numberOfCoupons.value)
					console.log(res)
					for(let i=0;i<res.data.value.length;i++){
						if(res.data.value[i].amountFull<=orderAmount.value){
							numberOfCoupons.value++
							coupons.value.push(res.data.value[i])
						}
					}
					//numberOfCoupons.value=res.data.value.length
					uni.$on('backWithData', data => {
					   // 在这里处理传递过来的数据
					   numbers.value=""
					   discount.value=""
					   console.log(2,+data.index);
					   couponNo.value=coupons.value[+data.index].couponNo
					   console.log(3,couponNo.value)
					   uni.$off('backWithData');
					   if(coupons.value[+data.index].couponFavorable){
						   numbers.value=coupons.value[+data.index].couponFavorable
					   }else{
						   discount.value=coupons.value[+data.index].couponDiscount
					   }
					   uni.request({
					   	url: getApp().globalData.baseUrl + "/album/settleaccount",
					   	method: "POST",
					   	header: {
					   		'content-type': 'application/json',
					   		'Access-Control-Allow-Origin': "*",
					   		'Authorization': uni.getStorageSync('token')
					   	},
					   	data: {
					   		couponNo: coupons.value[+data.index].couponNo,
							shootAddressId: getApp().globalData.album.shootAddressId,
							photoIds: photoIds.value,
							albumId: getApp().globalData.album.id,
							favorable:true
					   	},
					   	success: (res) => {
					   		console.log(res)
							discountAmount.value=res.data.value.favorableAmount
							payAmount.value=res.data.value.amount
					   	},
					   	fail: (err) => {
					   		console.log(err)
					   	}
					   })
					 });
					 console.log(numbers.value,discount.value)
				},
				fail: (err) => {
					console.log(err)
				}
			})
		}
	})
	onMounted(()=>{
		getColumnHeight()
	})
</script>
<style lang="less">
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-image: linear-gradient(to bottom,#d95e7d,#ffffff);
	}
	.order_balance {
		background-color: transparent;
		width: 100vw;
		//height: 95vh;
	}
	
	.coupon {
		position: relative;
	
		.couponLeft {
			float: left;
			margin-bottom: 20rpx;
			width: 50%;
		}
	
		.couponRight {
			float: right;
			margin-bottom: 20rpx;
			width: 50%;
			text-align: right;
		}
	}
	
	.photo_list {
		display: flex;
		align-items: center;
		width: 100%;
		flex-wrap: wrap;
	}
	
	.photol_item {
		width: 19%;
		height: 100rpx;
		margin: 0 6rpx;
	}
	
	.photol_item image {
		width: 90%;
		height: 92%;
	}
	
	.order_info {
		margin-top: 10rpx;
		font-weight: 600;
	}
	
	.payway {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	
	.payway image {
		width: 300rpx;
		height: 84rpx;
	}
	
	.balance_bottom {
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		height: 120rpx;
		background-color: #fff;
	
	}
	
	.balab_txt {
		font-size: 32rpx;
		font-weight: 600;
		margin-left: 10rpx;
	}
	.balab_favorable{
		font-size: 28rpx;
		color: #e77c90;
	}
	.balab_btn button {
		background-color: #e77c90;
		border-radius: 40rpx;
		color: #fff;
		margin-right: 10rpx;
		font-size: 32rpx;
	}
</style>